﻿using AutoMapper;
using MediatR;
using System;
using System.Threading.Tasks;
using System.Threading;
using EWC.HIS.Domain.Repositories;
using EWC.Core.DependencyInjection;
using EWC.Core.Util.CustomException;
using EWC.HIS.Application.Contracts.AppointmentRegistrationService.Commands;

namespace EWC.HIS.Application.AppointmentRegistrations.Handlers
{
    public class UpdateAppointmentRegistrationCommandHandler : IRequestHandler<UpdateAppointmentRegistrationCommand, bool>, ITransientDependency
    {
        private readonly IMapper _mapper;
        private readonly IAppointmentRegistrationRepository _appointmentRegistrationRepository;

        public UpdateAppointmentRegistrationCommandHandler(IMapper mapper, IAppointmentRegistrationRepository appointmentRegistrationRepository)
        {
            _mapper = mapper;
            _appointmentRegistrationRepository = appointmentRegistrationRepository;
        }

        public async Task<bool> Handle(UpdateAppointmentRegistrationCommand request, CancellationToken cancellationToken)
        {
            var existing = await _appointmentRegistrationRepository.GetAppointmentRegistrationByIdAsync(request.RegistrationDto.Id);

            if (existing == null)
            {
                throw new ArgumentException($"预约注册 ID = {request.RegistrationDto.Id} 未找到");
            }

            var updated = _mapper.Map(request.RegistrationDto, existing);
            return await _appointmentRegistrationRepository.UpdateAppointmentRegistrationAsync(updated);
            //throw new UserFriendlyException("ss");
        }
    }
}
